<template>
  <div class="cart">
    <van-nav-bar title="购物车" />
    <van-skeleton v-if="!hasList">
      <template #template>
        <div :style="{ display: 'flex', width: '100%' }">
          <van-skeleton-image />
          <div :style="{ flex: 1, marginLeft: '16px' }">
            <van-skeleton-paragraph row-width="60%" />
            <van-skeleton-paragraph />
            <van-skeleton-paragraph />
            <van-skeleton-paragraph />
          </div>
        </div>
      </template>
    </van-skeleton>
    <div class="List">
      <template v-for="(item, index) in List" :key="index">
        <van-checkbox-group
          @change="checkedResultChange"
          v-model="checkedResult"
          class="cart-item"
        >
          <van-checkbox
            :name="item.id"
            :key="item.id"
            checked-color="#1ba784"
            class="c-radio"
          />
          <van-swipe-cell :before-close="beforeClose">
            <van-card
              class="goods-card"
              :thumb="`${urlHost}${item.product_img}`"
            >
              <template #price>
                <span class="product-price"
                  >￥{{ item.product_price * item.quantity }}</span
                >
              </template>
              <template #title>
                <span class="product-title">{{ item.product_name }}</span>
              </template>
              <template #footer>
                <van-stepper v-model="item.quantity" />
              </template>
            </van-card>
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
              />
            </template>
          </van-swipe-cell>
        </van-checkbox-group>
      </template>
    </div>
    <van-submit-bar
      :button-color="red"
      :price="totalPrice"
      button-text="去结算"
      @submit="onSubmit"
    >
      <van-checkbox
        v-model="allChecked"
        :indeterminate="isIndeterminate"
        @change="checkAllChange"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user.store'
import { getCartList, delCart, updateCart } from '@/api/modules/cart'
import { showConfirmDialog, showSuccessToast } from 'vant'
import { fa } from 'element-plus/es/locales.mjs'
const router = useRouter()
const store = useUserStore()
const red = ref('#FF3800')
const urlHost = import.meta.env.VITE_APP_URL
const hasList = ref(false)

const List = ref([]) // 购物车列表
const allChecked = ref(false) // 全选
const isIndeterminate = ref(false)
// =======================购物车操作=======================
// 计算总价格
const totalPrice = ref(0)
const checkedResult = ref([]) // 选中的商品

const checkedResultChange = (val) => {
  console.log(val)
  // checkedResult.value = val
  const checkedCount = val.length
  allChecked.value = checkedCount === List.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < List.value.length
  totalPrice.value = List.value
    .filter((item) => val.includes(item.id))
    .reduce((prev, cur) => prev + cur.product_price * cur.quantity * 100, 0)
}

const checkAllChange = (val) => {
  checkedResult.value = val ? List.value.map((item) => item.id) : []
  isIndeterminate.value = false
}

// 监听购物车列表变化并更新总价格
watch(
  List,
  (newVal) => {
    totalPrice.value = newVal
      .filter((item) => checkedResult.value.includes(item.id))
      .reduce((prev, cur) => prev + cur.product_price * cur.quantity * 100, 0)
  },
  { deep: true }
)
// 获取购物车列表
const getList = async () => {
  const {
    userInfo: { app_user_id: user_id }
  } = store.$state
  try {
    const { data } = await getCartList({ user_id })

    List.value = data.data
    hasList.value = true
  } catch (error) {
    console.log(error)
  }
}

// position 为关闭时点击的位置
const beforeClose = ({ position }) => {
  switch (position) {
    case 'left':
    case 'cell':
    case 'outside':
      return true
    case 'right':
      return new Promise((resolve) => {
        showConfirmDialog({
          title: '确定删除吗？'
        })
          .then(() => {
            console.log(1)
            const info = {
              userId: store.$state.userInfo.app_user_id,
              productId: List.value[0].product_id
            }
            delCart(info)
              .then(() => {
                // 提示删除成功
                showSuccessToast('删除成功')
                getList()
                resolve(true)
              })
              .catch(() => resolve(false))
          })
          .catch(() => resolve(false))
      })
  }
}

// =======================购物车操作=======================

// =======================提交订单=======================
const onSubmit = () => {
  // 保存已选中的商品
  const checkedList = List.value.filter((item) =>
    checkedResult.value.includes(item.id)
  )
  if (checkedList.length === 0) return showSuccessToast('请选择商品并提交')
  router.push({
    name: 'OrderConfirm',
    query: {
      list: JSON.stringify(checkedList)
    }
  })
}
// =======================提交订单=======================

// ======================生命周期==========================
onMounted(() => {
  getList()
})
// ======================生命周期==========================
</script>

<style lang="less" scoped>
.van-submit-bar {
  position: fixed;
  bottom: 50px;
  width: 100%;
}
/deep/ .van-checkbox__icon--checked .van-icon {
  background-color: #1ba784;
  border-color: #1ba784;
}
/deep/ .van-checkbox__icon--indeterminate .van-icon {
  background-color: #1ba784;
  border-color: #1ba784;
}

.goods-card {
  margin: 0;
  background-color: #fff;
}

.delete-button {
  height: 100%;
}
.product-price {
  color: #ff3800;
  font-size: 20px;
  padding-left: 10px;
}
.product-title {
  font-size: 16px;
}

.c-radio {
  // margin: 0;
  width: 50px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #f7f7f7;
}
</style>
